import { useForm } from 'react-hook-form';
import { useDispatch } from 'react-redux';
import Button from 'src/component/Button';
import Form from 'src/component/Form';
import FormInput from 'src/component/FormInput';
import Modal from 'src/component/Modal';
import { openSnackbar } from 'src/redux/uiSlice';
import { editName } from 'src/service/userService'
import style from './EditDisplayNameModal.module.scss';

type EditDisplayNameForm = {
    displayName: string
}

type Props = {
    open: boolean;
    handleClose: () => void;
};

const EditDisplayNameModal = ({ open, handleClose }: Props) => {
    const dispatch = useDispatch();
    const methods = useForm<EditDisplayNameForm>();
    const token = localStorage.getItem('token')
    const uMail = localStorage.getItem('uMail')

    const onSubmit = (dataForm: EditDisplayNameForm) => {
        methods.reset();
        handleClose();

        editName({
            uMail: uMail,
            token: token,
            uName: dataForm.displayName
        }).then((res) => {
            if (res.success) {
                dispatch(openSnackbar({ message: res.message, severity: 'notify' }))
            } else {
                dispatch(openSnackbar({ message: res.message, severity: 'alert' }))
            }
        }).catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));



    };

    return (
        <Modal open={open} handleClose={handleClose}>
            <Form className={style.self} methods={methods} onSubmit={onSubmit}>
                <div className={style.heading}>变更显示名称</div>
                <div className={style.labelInput}>
                    <FormInput
                        label="显示名称"
                        name="displayName"
                        type="text"
                        required
                        asterisked
                    />
                </div>
                <div className={style.submitButton}>
                    <Button type="submit">送出</Button>
                </div>
            </Form>
        </Modal>
    );
};

export default EditDisplayNameModal;
